let d1RowsLock = 0;
$NG.AllReady(function (page, { useValuesChange, useClick, useUpdateRow, useUpdateRows, useDataIndexChange }) {
  console.log("Data ready event triggered");
  var mstform = $NG.getCmpApi("p_form_invoice_apply_m");
  var dgrid = $NG.getCmpApi("p_form_invoice_apply_d");
  //创建高级对象，间接实现监听字段
  // function _sum(){
  //     $NG.updateState((updater)=>{
  //         updater.data.p_form_invoice_apply_m.setProps({
  //             MyEventObject:MyEventObject._u_xfyh,
  //             MyEventObject:MyEventObject._u_gfyh,
  //         })
  //     })
  //         GetBankInfoByPhid(MyEventObject._u_gfyh?.value,'gf')
  //         GetBankInfoByPhid(MyEventObject._u_xfyh?.value, 'xf')
  // }
  // const MyEventObject = {
  //     _u_xfyh:null,
  //     _u_gfyh:null,
  //     set u_xfyh(value){
  //         this._u_xfyh = {...value}
  //        _sum()
  //     },
  //     set u_gfyh(value){
  //         console.log(`这个value`,value);
  //         this._u_gfyh = {...value}
  //         console.log(`这个value`,this._u_gfyh,this._u_xfyh);
  //         _sum()
  //     }
  // }
  //页面条件
  if (page.oType == "add" || page.oType == "edit") {
    $NG.execServer("getEpmInfoByUserID", { phid: $NG.getUser().userID }, (res) => {
      const datas = JSON.parse(res.data)[0].extendObjects;
      console.log(datas);
      //   开票申请里的发票类型改为手填20241225
      //   console.log("拿去合同号带出来的发票类型", mstform.getItem("u_invoice_type"));
      //更新UI表格
      $NG.updateState((updater) => {
        //【注意这里的表名不能为控件ID，必须要是表名】
        updater.data.p_form_invoice_apply_m.setProps({
          u_hr_apply: {
            value: datas.hem_phid,
            label: datas.hem_name,
          },
        });
      });
    });
    calculationPay();
  }
  function init() {
    $NG.updateState((updater) => {
      updater.data.p_form_invoice_apply_m.setProps({
        u_invoice_dt: formatDate(new Date(), "yyyy-mm-dd"),
      });
    });
  }
  //监听汇款差额
  useValuesChange(({ args }) => {
    const _data = args[0].u_hkkpce;

    //表头多字段设置属性
    $NG.updateUI((updater) => {
      if (Number(_data) < 0) {
        updater.form.p_form_invoice_apply_m.u_hkcesm.setProps({
          required: true, //必输
        });
      } else {
        updater.form.p_form_invoice_apply_m.u_hkcesm.setProps({
          required: false, //必输
        });
      }
    });
  }, "p_form_invoice_apply_m.u_hkkpce");

  useValuesChange(({ args }) => {
    const _data = args[0].u_srkpce;
    //表头多字段设置属性
    $NG.updateUI((updater) => {
      if (Number(_data) < 0) {
        updater.form.p_form_invoice_apply_m.u_srcesm.setProps({
          required: true, //必输
        });
      }
    });
  }, "p_form_invoice_apply_m.u_srkpce");

  useValuesChange(({ args }) => {
    console.log(`监听银行`, args);
    GetBankInfoByPhid(mstform.getItem("u_gfyh").getValue(), "gf");
  }, "p_form_invoice_apply_m.u_gfyh");
  let _xfyh = null;
  let _gfyh = null;
  let _xfTime = 0
  let _gfTime = 0
  if(page.oType=='add'||page.oType=='edit'){
    _xfTime = setInterval(() => {
        try {
          if (mstform.getItem("u_xfyh").getValue() !== _xfyh) {
            _xfyh = mstform.getItem("u_xfyh").getValue();
            GetBankInfoByPhid(mstform.getItem("u_xfyh").getValue(), "xf");
          }
        } catch (err) {
          clearInterval(_xfTime);
          console.log(err);
          $NG.alert("自定义监听器报错，行号：108");
        }
      }, 1000);
    
      
      _gfTime = setInterval(() => {
        try {
          if (mstform.getItem("u_gfyh").getValue() !== _gfyh) {
            _gfyh = mstform.getItem("u_gfyh").getValue();
            GetBankInfoByPhid(mstform.getItem("u_gfyh").getValue(), "gf");
          }
        } catch (err) {
          clearInterval(_gfTime);
          console.log(err);
          $NG.alert("自定义监听器报错，行号：125");
        }
      }, 1000);
  }
  {
    //表头字段变化逻辑BEGIN
    useValuesChange(({ args }) => {
      getCntMInfoByPhid();
    }, "p_form_invoice_apply_m.u_cnt");
  } //表头字段变化逻辑END

  useUpdateRows(({ args }) => {
    const _data = args[0];
    // 分流操作，防止并发太多
    if (d1RowsLock) {
      clearTimeout();
    }
    d1RowsLock = setTimeout(() => {
      sumAmt();
    }, 600);
    // 默认数量为1
    args[0].forEach((item) => {
      if (!item.qty || item.qty < 0) {
        item.qty = 1;
      }
    });
    dgrid.refreshView();
  }, "p_form_invoice_apply_d");

  //优先性设置
  let _d_amt = 0;
  useUpdateRow(({ args }) => {
    console.log(args);
    const _data = args[0];
    if (_data.u_vat_prc && _data.taxrate) {
      _data.prc = Number(_data.u_vat_prc) / (1 + Number(_data.taxrate));
    }
    if (_data.u_jshj && _data.taxrate) {
      _data.amt = Number(_data.u_jshj) / (1 + Number(_data.taxrate));
      _data.u_ratee = Number((_data.u_jshj / (1 + _data.taxrate)) * _data.taxrate);
    }
    dgrid.refreshView();
  }, "p_form_invoice_apply_d");
  useDataIndexChange(({ args, table }) => {
    if (table.bindTable == "p_form_invoice_apply_d") {
      console.log("单字段监听", args, table);
      const _data = args[0];
      if (_data.qty && _data.u_vat_prc) {
        _data.u_jshj = _data.u_vat_prc * _data.qty;
      }
      dgrid.refreshView();
    }
  }, "u_vat_prc");

  useDataIndexChange(({ args }) => {
    if (table.bindTable == "p_form_invoice_apply_d") {
      const _data = args[0];
      if (_data.qty && _data.u_jshj) {
        _data.u_vat_prc = _data.u_jshj / _data.qty;
      }
      dgrid.refreshView();
    }
  }, "u_jshj");

  useDataIndexChange(({ args }) => {
    if (table.bindTable == "p_form_invoice_apply_d") {
      const _data = args[0];
      if (_data.qty && _data.u_jshj) {
        _data.u_vat_prc = _data.u_jshj / _data.qty;
      }
      dgrid.refreshView();
    }
  }, "qty");

  //根据合同id获取合同信息
  function getCntMInfoByPhid(params) {
    $NG.execServer("getCntMInfoByPhid", { phid: mstform.getItem("u_cnt").getValue() }, function (res) {
      const datas = JSON.parse(res.data)[0].extendObjects;
      // // 触发自定义监听更改
      // MyEventObject.u_gfyh =  {
      //         //银行名称
      //         value: datas.tick_taxbankid,
      //         label: datas.tick_taxbankname,
      //     }
      // MyEventObject.u_xfyh = {
      //         //银行名称
      //         value: datas.inv_taxbankid,
      //         label: datas.inv_taxbankname,
      //     }
      //帮助字段赋值
      $NG.updateState((updater) => {
        console.log("获取和同数据", datas);
        updater.data.p_form_invoice_apply_m.setProps({
          u_cnt_amt: datas.cnt_sum_vat_fc,
          u_cnt_no: datas.pcm_no,
          //购方信息（客户信息）（收票单位信息）
          u_gfmc: {
            //单位名称
            value: datas.tick_id,
            label: datas.tick_name,
          },
          u_gfbm: datas.tick_no, //单位编码
          u_gfsh: datas.tick_unisocialcredit, //社会信用代码
          u_gfdz: datas.tick_taxaddress, //单位地址
          u_gfdh: datas.tick_taxtelephone, //联系电话
          u_gfyh: {
            //银行名称
            value: datas.tick_taxbankid,
            label: datas.tick_taxbankname,
          },
          u_gfyhzh: datas.tick_taxaccountno, //银行账号
          //销方信息（供应商信息）（开票单位信息）
          u_xfmc: {
            //单位名称
            value: datas.inv_id,
            label: datas.inv_name,
          },
          inv_no: datas.inv_no, //单位编码
          u_xfsh: datas.inv_unisocialcredit, //社会信用代码
          u_xfdz: datas.inv_taxaddress, //单位地址
          u_xfdh: datas.inv_taxtelephone, //联系电话
          u_xfyh: {
            //银行名称
            value: datas.inv_taxbankid,
            label: datas.inv_taxbankname,
          },
          u_xfyhzh: datas.inv_taxaccountno, //银行账号
        });
      });
    });
  }
  // 通过项目过滤合同号 初始化
  cntMFilter();
  function cntMFilter() {
    console.log(`正在过滤`);
    $NG.updateUI((updater, state) => {
      getCntCount();
      updater.fieldSetForm.p_form_invoice_apply_m.u_cnt.setProps({
        onBeforeOpen: async () => {
          var phid_pc = $NG.getCmpApi("p_form_invoice_apply_m").getItem("phid_pc").getValue();
          console.log(`项目名：`, phid_pc);
          if (!phid_pc) {
            $NG.alert("请先选择项目");
            return false;
          } else {
            return true;
          }
        },
        ...(!!$NG.getCmpApi("p_form_invoice_apply_m").getItem("phid_pc").getValue() && {
          clientSqlFilter: {
            bill_type: 1, //合同类型
            phid_pc: $NG.getCmpApi("p_form_invoice_apply_m").getItem("phid_pc").getValue(),
          },
        }),
      });
    });
  }
  function getCntCount() {
    const phid = mstform.getItem("phid_pc").getValue();
    if (!phid) return;
    $NG.execServer("getCntCount", { type: 1, phid_pc: phid }, function (res) {
      console.log(res);
      if (res.count !== 0) {
        const _datas = JSON.parse(res.data);
        if (_datas.length === 1) {
          const _data = _datas[0].extendObjects;
          $NG.updateState((updater) => {
            updater.data.p_form_invoice_apply_m.setProps({
              u_cnt: {
                label: _data.bill_name,
                value: _data.phid,
              },
            });
            setTimeout(() => {
              getCntMInfoByPhid();
            }, 200);
          });
        }
      }
    });
  }
  // 监听字段项目
  useValuesChange(({ args }) => {
    cntMFilter();
    getProjectInfo();
    $NG.updateState((updater) => {
      updater.data.p_form_invoice_apply_m.setProps({
        u_cnt: {
          label: null,
          value: null,
        },
        u_cnt_no: null,
        u_cnt_amt: null,
      });
    });
  }, "p_form_invoice_apply_m.phid_pc");

  getEpmInfoByUserID();
  //根据所选组织获取往来单位信息
  function getEpmInfoByUserID(params) {
    $NG.execServer("getEnterpriseInfoByPhid", { phid: mstform.getValues().phid_org }, function (res) {
      console.log(`获取组织信息`, JSON.stringify(res));
      const datas = JSON.parse(res.data)[0].extendObjects;
      console.log("组织信息", datas);
      $NG.updateState((updater) => {
        updater.data.p_form_invoice_apply_m.setProps({
          u_xfmc: datas.compname,
          u_xfsh: datas.unisocialcredit,
          u_xfdz: datas.taxaddress,
          u_xfdh: datas.taxtelephone,
          u_xfyhzh: datas.bankno,
          u_xfyh: datas.taxbankname,
          u_xfhh: datas.taxaccountno,
        });
      });
    });
  }

  // 获取项目
  function getProjectInfo(isReturn = false, phid = mstform.getItem("phid_pc").getValue(), fun) {
    if (!mstform.getItem("phid_pc").getValue()) return;
    try {
      setTimeout(() => {
        $NG.execServer("getPtInfoByPhid", { phid: phid }, (res) => {
          const _data = JSON.parse(res.data)[0].extendObjects;
          console.log(`获取项目信息`, _data);
          if (isReturn) {
            fun(_data);
          } else {
            $NG.updateState((updater) => {
              updater.data.p_form_invoice_apply_m.setProps({
                u_pc_no: _data.pc_no, //项目编码
                phid_org: {
                  //事业部or组织
                  value: _data.org_phid,
                  label: _data.org_name,
                },
                phid_emp: {
                  label: _data.project_manager_name,
                  value: _data.project_manager_phid,
                },
                u_sqgw: {
                  //售前顾问
                  value: _data.user_sqgw_phid,
                  label: _data.user_sqgw_name,
                },
                u_regional_center: {
                  //区域中心
                  value: _data.regional_center_phid,
                  label: _data.regional_center_name,
                },
                u_product_line: {
                  //产品线
                  value: _data.midwife_phid,
                  label: _data.midwife_name,
                },
                u_dept: {
                  //部门
                  value: _data.dept_phid,
                  label: _data.dept_name,
                },
                u_pc_type: {
                  //项目类型
                  value: _data.type_phid,
                  label: _data.type_name,
                },
              });
            });
          }
        });
      }, 100);
    } catch (err) {
      $NG.alert("获取项目信息发生失败请检查~");
    }
  }

  //计算本次申请含税/未税金额表头
  function sumAmt() {
    const _arr = dgrid.getRows();
    let _count = 0;
    _arr.forEach((item) => {
      _count += Number(item.amt) || 0;
    });
    $NG.updateState((updater) => {
      updater.data.p_form_invoice_apply_m.setProps({
        u_amt_total_apply_vat: _count,
        u_amt_total_apply: _count,
      });
    });
  }

  //新增部分合同详细
  //通过数量和单价计算金额
  function calculationPay() {
    const arr = ["p_form_invoice_apply_d.u_qty", "p_form_invoice_apply_d.u_vat_prc", "p_form_invoice_apply_d.v_amt"];
    arr.forEach((item, index) => {
      useDataIndexChange(({ args, instance }) => {
        console.log(`监听----${item}`, args);
        args[0].u_amt = (args[0].u_qty || 0) * args[0].u_vat_prc || 0;
        instance.updateRow(args[0]);
      }, item);
    });
  }
  // 获取银行行号
  //根据银行主键获取银行信息
  function GetBankInfoByPhid(phid, str) {
    console.log(`检查传入的参数`, phid, str);
    if (!phid || !str) return;
    $NG.execServer("GetBankInfoByPhid", { phid: phid }, function (res) {
      const datas = JSON.parse(res.data)[0].extendObjects;
      console.log(datas);
      $NG.updateState((updater) => {
        if (str == "gf") {
          updater.data.p_form_invoice_apply_m.setProps({
            u_gfhh: datas.bankno, //银行行号
          });
        } else if (str == "xf") {
          updater.data.p_form_invoice_apply_m.setProps({
            u_xfhh: datas.bankno, //银行行号
          });
        }
      });
    });
  }
  // 格式化日期
  function formatDate(dateStr, outputFormat) {
    const date = new Date(dateStr);

    if (isNaN(date)) {
      return "无效的日期字符串";
    }

    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, "0");
    const day = String(date.getDate()).padStart(2, "0");
    const hours = String(date.getHours()).padStart(2, "0");
    const minutes = String(date.getMinutes()).padStart(2, "0");

    let formattedDate;

    switch (outputFormat) {
      case "yyyy-mm-dd":
        formattedDate = `${year}-${month}-${day}`;
        break;
      case "yyyy-mm-dd HH:mm":
        formattedDate = `${year}-${month}-${day} ${hours}:${minutes}`;
        break;
      case "yyyy-mm":
        formattedDate = `${year}-${month}`;
        break;
      // 可以根据需要继续添加其他格式的处理逻辑
      default:
        formattedDate = "不支持的输出格式";
    }

    return formattedDate;
  }
});
